// 全选/取消全选功能
function toggleSelectAll() {
    var selectAllCheckbox = document.getElementById('selectAll');
    var checkboxes = document.querySelectorAll('.page-checkbox');
    checkboxes.forEach(function(checkbox) {
        checkbox.checked = selectAllCheckbox.checked;
    });
    toggleBatchDeleteButton();
}

// 页面加载完成后添加事件监听器
document.addEventListener('DOMContentLoaded', function() {
    // 为全选框添加事件监听
    var selectAllCheckbox = document.getElementById('selectAll');
    if (selectAllCheckbox) {
        selectAllCheckbox.addEventListener('change', toggleSelectAll);
    }
    
    // 为所有复选框添加事件监听
    var checkboxes = document.querySelectorAll('.page-checkbox');
    checkboxes.forEach(function(checkbox) {
        checkbox.addEventListener('change', toggleBatchDeleteButton);
    });
    
    // 为批量删除按钮添加事件监听
    var batchDeleteBtn = document.getElementById('batchDeleteBtn');
    if (batchDeleteBtn) {
        batchDeleteBtn.addEventListener('click', submitBatchDelete);
    }
});

// 根据选中状态启用/禁用批量删除按钮
function toggleBatchDeleteButton() {
    var checkboxes = document.querySelectorAll('.page-checkbox:checked');
    var batchDeleteBtn = document.getElementById('batchDeleteBtn');
    batchDeleteBtn.disabled = checkboxes.length === 0;
}

// 提交批量删除表单
function submitBatchDelete() {
    var checkboxes = document.querySelectorAll('.page-checkbox:checked');
    if (checkboxes.length === 0) {
        createNotification('请先选择要删除的静态网页', 'error');
        return;
    }
    
    if (confirm('确定要删除选中的静态网页吗？此操作将同时删除所有相关文件，且无法恢复。')) {
        var formData = new FormData();
        checkboxes.forEach(function(checkbox) {
            formData.append('page_ids', checkbox.value);
        });
        
        fetch('/admin/static-pages/batch-delete', {
            method: 'POST',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: formData
        })
        .then(function(response) {
            return response.json();
        })
        .then(function(data) {
            if (data.success) {
                // 添加删除动画效果
                checkboxes.forEach(function(checkbox) {
                    var row = checkbox.closest('tr');
                    row.style.transition = 'all 0.3s ease';
                    row.style.height = row.offsetHeight + 'px';
                    
                    // 触发重排
                    void row.offsetHeight;
                    
                    row.style.height = '0';
                    row.style.opacity = '0';
                    row.style.padding = '0';
                    row.style.margin = '0';
                    
                    // 动画结束后移除元素
                    setTimeout(function() {
                        row.remove();
                        // 如果所有行都被删除，更新全选状态
                        if (document.querySelectorAll('tbody tr').length === 0) {
                            document.getElementById('selectAll').checked = false;
                            toggleBatchDeleteButton();
                        }
                    }, 300);
                });
                
                // 清空选中状态并禁用批量删除按钮
                document.getElementById('selectAll').checked = false;
                toggleBatchDeleteButton();
                
                createNotification(data.message, 'success');
            } else {
                createNotification(data.message, 'error');
            }
        })
        .catch(function(error) {
            createNotification('删除失败，请重试', 'error');
        });
    }
}

// 单个删除功能
document.addEventListener('click', function(event) {
    if (event.target.classList.contains('delete-btn')) {
        var button = event.target;
        var pageId = button.getAttribute('data-id');
        var pageName = button.getAttribute('data-name');
        
        if (confirm('确定要删除静态网页 "' + pageName + '" 吗？此操作将同时删除所有相关文件，且无法恢复。')) {
            var formData = new FormData();
            
            fetch('/admin/static-pages/delete/' + pageId, {
                method: 'POST',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: formData
            })
            .then(function(response) {
                return response.json();
            })
            .then(function(data) {
                if (data.success) {
                    // 添加删除动画效果
                    var row = button.closest('tr');
                    row.style.transition = 'all 0.3s ease';
                    row.style.height = row.offsetHeight + 'px';
                    
                    // 触发重排
                    void row.offsetHeight;
                    
                    row.style.height = '0';
                    row.style.opacity = '0';
                    row.style.padding = '0';
                    row.style.margin = '0';
                    
                    // 动画结束后移除元素
                    setTimeout(function() {
                        row.remove();
                        // 如果所有行都被删除，更新全选状态
                        if (document.querySelectorAll('tbody tr').length === 0) {
                            document.getElementById('selectAll').checked = false;
                            toggleBatchDeleteButton();
                        }
                    }, 300);
                    
                    createNotification(data.message, 'success');
                } else {
                    createNotification(data.message, 'error');
                }
            })
            .catch(function(error) {
                createNotification('删除失败，请重试', 'error');
            });
        }
    }
});

// 文件管理按钮点击事件
document.querySelectorAll('.file-btn').forEach(function(btn) {
    btn.addEventListener('click', function() {
        var id = this.getAttribute('data-id');
        window.location.href = '/admin/static-pages/files/' + id;
    });
});

// 状态切换功能 - 修复需要点击两次才能禁用的问题
document.addEventListener('click', function(event) {
    if (event.target.classList.contains('toggle-status-btn')) {
        var button = event.target;
        var pageId = button.getAttribute('data-id');
        // 获取当前状态，使用按钮的data-status属性
        var currentStatus = button.getAttribute('data-status') === 'true';
        // 计算目标状态
        var targetStatus = !currentStatus;
        var confirmText = targetStatus ? '确定要启用此静态网页吗？' : '确定要禁用此静态网页吗？禁用后该页面将无法访问。';
        
        if (confirm(confirmText)) {
            // 发送请求到服务器切换状态
            fetch('/admin/static-pages/toggle-status/' + pageId, {
                method: 'POST',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ new_status: targetStatus })
            })
            .then(function(response) {
                return response.json();
            })
            .then(function(data) {
                if (data.success) {
                    // 关键修复：直接使用targetStatus更新UI，确保与服务器状态一致
                    // 避免任何可能的状态不同步问题
                    
                    // 立即更新按钮的data-status属性，确保下一次点击使用正确状态
                    button.setAttribute('data-status', targetStatus.toString());
                    
                    // 更新按钮样式和文本
                    button.className = 'btn btn-xs ' + (targetStatus ? 'btn-warning' : 'btn-success') + ' toggle-status-btn';
                    button.textContent = targetStatus ? '禁用' : '启用';
                    
                    // 更新状态显示文本
                    var statusSpan = button.previousElementSibling;
                    statusSpan.textContent = targetStatus ? '启用' : '禁用';
                    statusSpan.style.color = targetStatus ? '#2ecc71' : '#e74c3c';
                    
                    createNotification(data.message, 'success');
                } else {
                    createNotification(data.message, 'error');
                }
            })
            .catch(function(error) {
                createNotification('状态切换失败，请重试', 'error');
            });
        }
    }
});

// 通知函数
function createNotification(message, type) {
    if (type === undefined) {
        type = 'info';
    }
    // 创建通知元素
    var notification = document.createElement('div');
    notification.className = 'notification ' + type;
    notification.textContent = message;
    
    // 设置样式
    notification.style.position = 'fixed';
    notification.style.top = '20px';
    notification.style.right = '20px';
    notification.style.padding = '15px 20px';
    notification.style.borderRadius = '5px';
    notification.style.color = 'white';
    notification.style.fontWeight = 'bold';
    notification.style.zIndex = '9999';
    notification.style.opacity = '0';
    notification.style.transition = 'all 0.3s ease';
    notification.style.boxShadow = '0 2px 10px rgba(0, 0, 0, 0.2)';
    
    // 根据类型设置背景颜色
    if (type === 'success') {
        notification.style.backgroundColor = '#2ecc71';
    } else if (type === 'error') {
        notification.style.backgroundColor = '#e74c3c';
    } else if (type === 'warning') {
        notification.style.backgroundColor = '#f39c12';
    } else {
        notification.style.backgroundColor = '#3498db';
    }
    
    // 添加到页面
    document.body.appendChild(notification);
    
    // 触发动画
    setTimeout(function() {
        notification.style.opacity = '1';
        notification.style.top = '20px';
    }, 10);
    
    // 3秒后消失
    setTimeout(function() {
        notification.style.opacity = '0';
        notification.style.top = '-100px';
        
        // 动画结束后移除元素
        setTimeout(function() {
            document.body.removeChild(notification);
        }, 300);
    }, 3000);
}